package ua.org.tumakha.resume.xml.transform;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import javax.xml.transform.Result;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamSource;

import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.apps.Fop;
import org.apache.fop.apps.FopFactory;
import org.apache.fop.apps.MimeConstants;
import org.xml.sax.SAXException;

/**
 * @author Yuriy Tumakha
 */
public class FoTransformer extends XslTransformer {

    private static FopFactory fopFactory = FopFactory.newInstance();
    private static FOUserAgent foUserAgent = fopFactory.newFOUserAgent();

    public FoTransformer(File styleSheetFile, String fileExtension) throws TransformerConfigurationException,
            IOException, SAXException, ConfigurationException {
        super(styleSheetFile, fileExtension);
        foUserAgent.setProducer("XSL-FO");
        foUserAgent.setCreator("Yuriy Tumakha");
        foUserAgent.setAuthor("Yuriy Tumakha");
        foUserAgent.setCreationDate(new Date());
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("fop.xconf");
        Configuration cfg = new DefaultConfigurationBuilder().build(is);
        fopFactory.setUserConfig(cfg);
    }

    @Override
    public boolean transform(File xmlSource) throws Exception {
        File resultFile = getResultFile(xmlSource);
        OutputStream out = new BufferedOutputStream(new FileOutputStream(resultFile));
        String mimeType = MimeConstants.MIME_RTF;
        if (getFileExtension().equals(".pdf")) {
            mimeType = MimeConstants.MIME_PDF;
        }
        try {
            Fop fop = fopFactory.newFop(mimeType, foUserAgent, out);
            Result res = new SAXResult(fop.getDefaultHandler());
            transformer.transform(new StreamSource(xmlSource), res);
        } finally {
            out.close();
        }
        return true;
    }

}
